package com.it.mydream.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.it.mydream.Bean.Rank;
import com.it.mydream.Bean.Seed;
import com.it.mydream.Bean.User;
import com.it.mydream.Service.imp.LoginServiceImp;
import com.it.mydream.Service.imp.RankServiceImp;
import com.it.mydream.Service.imp.SeedServiceImp;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class WuziqiController {

    @Autowired
    private RankServiceImp rkService;
    @Autowired
    private SeedServiceImp sdService;
    @Autowired
    private LoginServiceImp loginService;

    @RequestMapping("goWuZiQi")
    public String goWuZiQi(HttpServletRequest request){
        HttpSession session = request.getSession();
        ServletContext application = request.getServletContext();
        User user = (User) session.getAttribute("user");
        user.setUser_status("20007");
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setUser_status_time(sdf.format(System.currentTimeMillis()));
        loginService.updateUserStatus(user);

        List<User> userlist = loginService.getUserList();
        application.setAttribute("userlist",userlist);

        List<Rank> ranks = rkService.selectRanks("30002");
        request.setAttribute("ranks",ranks);
        return "game/wuziqi";
    }

    @RequestMapping("uploadRankForadd")
    @ResponseBody
    public void uploadRankForadd(HttpServletRequest request){
        String type = request.getParameter("type");
        String score = request.getParameter("score");

        HttpSession session = request.getSession();
        ServletContext application = request.getServletContext();
        User user = (User) session.getAttribute("user");

        Rank rank_t = new Rank();
        rank_t.setUser(user);
        rank_t.setType(type);
        Rank rank = rkService.selectRank(rank_t);
        if(rank == null){
            rank_t.setScore(score);
            rank_t.setCount("1");
            rkService.insertRank(rank_t);
        }else{
            String o_score = rank.getScore();
            String o_count = rank.getCount();
            if(score.equals("1")){
                rank.setScore(String.valueOf(Integer.parseInt(o_score)+1));
            }
            rank.setCount(String.valueOf(Integer.parseInt(o_count)+1));
            rank.setType(type);
            rkService.updateRank(rank);
        }
    }

    @RequestMapping("createSr")
    @ResponseBody
    public String createSr(HttpServletRequest request){
        HttpSession session = request.getSession();
        ServletContext application = request.getServletContext();
        User user = (User) session.getAttribute("user");
        user.setUser_status("20007");
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setUser_status_time(sdf.format(System.currentTimeMillis()));
        loginService.updateUserStatus(user);

        List<User> userlist = loginService.getUserList();
        application.setAttribute("userlist",userlist);

        String n = request.getParameter("n");
        String user1_id = "";
        String user2_id = "";
        List<Map<String, Object>> list = (List<Map<String, Object>>) application.getAttribute("DTList");
        Map<String, Object> map = list.get(Integer.parseInt(n));
        if(n != null||!n.equals("")){
            user1_id = String.valueOf(((User)map.get("user1")).getUser_id());
            user2_id = String.valueOf(((User)map.get("user2")).getUser_id());
        }else{
            user1_id = (String) request.getAttribute("user1_id");
            user2_id = (String) request.getAttribute("user2_id");
        }

        SimpleDateFormat sdf1= new SimpleDateFormat("yyyyMMddHHmmss");
        String time = sdf1.format(System.currentTimeMillis());
        Random rand = new Random();
        String random = String.format("%02d",rand.nextInt(99)+1);
        String seed_code = user1_id + user2_id + time + random;
        String partman = user1_id + "," +user2_id;
        List<int[]> l = new ArrayList<>();
        l.add(new int[] {-1,-1});
        ObjectMapper objectMapper = new ObjectMapper();
        String seed_text = "";
        try {
            String json = objectMapper.writeValueAsString(l);
            seed_text = json;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Seed seed = new Seed();
        seed.setSeed_code(seed_code);
        seed.setCreatetime(sdf.format(System.currentTimeMillis()));
        seed.setSeed_type("40001");
        seed.setCreateman(user.getUser_id());
        seed.setPartman(partman);
        seed.setSeed_text(seed_text);
        sdService.insertSeed(seed);

        map.put("seed",seed_code);
        map = new HashMap<>(map);
        list.set(Integer.parseInt(n), map);
        application.setAttribute("DTList", list);

        Map<String,Seed> seedlist = (Map<String, Seed>) application.getAttribute("seedlist");
        seedlist.put(seed_code,seed);
        application.setAttribute("seedlist",seedlist);

        return seed_code;
    }

    @RequestMapping("gosrWuZiQi")
    public String gosrWuZiQi(HttpServletRequest request){
        HttpSession session = request.getSession();
        ServletContext application = request.getServletContext();
        User user = (User) session.getAttribute("user");
        user.setUser_status("20007");
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setUser_status_time(sdf.format(System.currentTimeMillis()));
        loginService.updateUserStatus(user);

        List<User> userlist = loginService.getUserList();
        application.setAttribute("userlist",userlist);

        List<Rank> ranks = rkService.selectRanks("30002");
        request.setAttribute("ranks",ranks);

        String n = request.getParameter("n");
        String seed = request.getParameter("seed");
        String user1_id = "";
        String user2_id = "";
        if(n != null&&!n.equals("")){
            List<Map<String, Object>> list = (List<Map<String, Object>>) application.getAttribute("DTList");
            Map<String, Object> map = list.get(Integer.parseInt(n));
            user1_id = String.valueOf(((User)map.get("user1")).getUser_id());
            user2_id = String.valueOf(((User)map.get("user2")).getUser_id());
        }else{
            user1_id = (String) request.getAttribute("user1_id");
            user2_id = (String) request.getAttribute("user2_id");
        }

        request.setAttribute("seed",seed);
        request.setAttribute("user1_id",user1_id);
        request.setAttribute("user2_id",user2_id);
        request.setAttribute("user",user);

        return "game/srwuziqi";
    }

    @RequestMapping("getDs")
    @ResponseBody
    public Map<String, Integer> getDs(HttpServletRequest request) {
        ServletContext application = request.getServletContext();
        HttpSession session = request.getSession();

        String user_id = request.getParameter("user_id");
        String seed_code = request.getParameter("seed");

        Map<String,Seed> seedlist = (Map<String, Seed>) application.getAttribute("seedlist");
        Seed seed = seedlist.get(seed_code);
        if(seed != null){
            String json = seed.getSeed_text();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<int[]> list = objectMapper.readValue(json, new TypeReference<List<int[]>>() {});
                int[] i = list.get(list.size()-1);
                int u = i[0];
                int v = i[1];
                Map<String, Integer> map = new HashMap<String, Integer>();
                map.put("u",u);
                map.put("v",v);
                return map;
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @RequestMapping("setQz")
    @ResponseBody
    public void setQz(HttpServletRequest request) {
        ServletContext application = request.getServletContext();
        HttpSession session = request.getSession();

        String user_id = request.getParameter("user_id");
        String seed_code = request.getParameter("seed");
        String v = request.getParameter("v");
        String u = request.getParameter("u");

        Map<String,Seed> seedlist = (Map<String, Seed>) application.getAttribute("seedlist");
        Seed seed = seedlist.get(seed_code);
        if(seed != null){
            String json = seed.getSeed_text();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<int[]> list = objectMapper.readValue(json, List.class);
                int[] i = new int[2];
                i[0] = Integer.parseInt(u);
                i[1] = Integer.parseInt(v);
                list.add(i);
                String newjson = objectMapper.writeValueAsString(list);
                seed.setSeed_text(newjson);
                seedlist.put(seed_code,seed);
                application.setAttribute("seedlist",seedlist);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @RequestMapping("srEnd")
    @ResponseBody
    public void srEnd(HttpServletRequest request) {
        ServletContext application = request.getServletContext();
        HttpSession session = request.getSession();

        String user_id = request.getParameter("user_id");
        String seed_code = request.getParameter("seed");

        Map<String,Seed> seedlist = (Map<String, Seed>) application.getAttribute("seedlist");
        Seed seed = seedlist.get(seed_code);
        seed.setWinman(user_id);
        if(seed != null){
            sdService.updateSeed(seed);
        }
    }

}
